//
//  HostLikeViewController.m
//  SuperRadio
//
//  Created by Damon on 14/12/17.
//  Copyright (c) 2014年 三个臭皮匠. All rights reserved.
//

#import "HostLikeViewController.h"
#import "AlbumDatailsOfList.h"
#import "AlbumDetailsCell.h"
#import "NetHandler.h"
#import "Introduction.h"
#import "UIScrollView+MJRefresh.h"
#import "UIScrollView+Extension.h"

#import "MainPlayerViewController.h"

#import "AudioPlayer.h"
#import "AudioButton.h"

@interface HostLikeViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) NSMutableArray *arr;
@property (nonatomic, retain) UITableView *hostLikeView;

// 当前的请求页数
@property (nonatomic, assign) NSInteger pageId;
// 最大得页数
@property (nonatomic, assign) NSInteger maxPageId;

@property (nonatomic, assign) NSInteger cellTag;

@property (nonatomic, retain)AudioButton *audioBtn;

@property(nonatomic, retain) MainPlayerViewController *mainPlayVC;

@property (nonatomic, retain)AlbumDetailsCell *cell;

@end

@implementation HostLikeViewController

#pragma mark 初始化
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.pageId = 1;
        self.arr = [NSMutableArray array];

    }
    return self;
}



#pragma mark 数据处理
- (void)handleData
{
    
    NSString *pageId = [NSString stringWithFormat:@"%ld", self.pageId];

    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/favorite?device=iPhone&pageId=%@&pageSize=30&toUid=%@", pageId,self.introduction.uid];
    
    [NetHandler getDataWithURL:str completion:^(NSData *data) {
        
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

        self.pageId = [[result objectForKey:@"pageId"] integerValue];
        self.maxPageId = [[result objectForKey:@"maxPageId"] integerValue];
        NSMutableArray *likeArr = [result objectForKey:@"list"];
 
        for (NSDictionary *dic in likeArr) {
            
            AlbumDatailsOfList *list = [[AlbumDatailsOfList alloc] initWithDictionary:dic];

            [self.arr addObject:list];

            [list release];
        }

        if (self.arr.count != 0) {
            //self.automaticallyAdjustsScrollViewInsets = YES;

             [self.view addSubview:self.hostLikeView];
             [self.hostLikeView reloadData];
        } else {
            UIImageView *likeImage = [[UIImageView alloc] initWithFrame:self.view.frame];
            likeImage.image = [UIImage imageNamed:@"back3.jpg"];
            [self.view addSubview:likeImage];
            [likeImage release];
        }
       
    }];
}



- (void)setupRefresh
{
    //    NSLog(@"进入了setupRefresh");
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    
    //    [self.detailsTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //    //进入刷新状态(一进入程序就下拉刷新)
    //    [self.detailsTableView headerBeginRefreshing];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.hostLikeView addFooterWithTarget:self action:@selector(footerRereshing)];
}



#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    
    //1. 在这调用请求网络数据方法（刷新数据）
    
    //2. 2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.hostLikeView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.hostLikeView headerEndRefreshing];
    });
}

//   进入加载状态
- (void)footerRereshing
{
    //1. 拼接口等操作
    // 请求加载数据
    
    // 如果是音频列表
    
    // 小于最大页码
    if (self.pageId < self.maxPageId) {
        // 页码加1
        ++self.pageId;
        
        
        
        NSString *pageId = [NSString stringWithFormat:@"%ld", self.pageId];
        
        NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/favorite?device=iPhone&pageId=%@&pageSize=30&toUid=%@", pageId, self.introduction.uid];
        
        [NetHandler getDataWithURL:str completion:^(NSData *data) {
            
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            
            self.pageId = [[result objectForKey:@"pageId"] integerValue];
            self.maxPageId = [[result objectForKey:@"maxPageId"] integerValue];
            
            NSMutableArray *likeArr = [result objectForKey:@"list"];
            
            for (NSDictionary *dic in likeArr) {
                
                AlbumDatailsOfList *list = [[AlbumDatailsOfList alloc] initWithDictionary:dic];
                
                [self.arr addObject:list];
                
                [list release];
            }
            
            if (self.arr.count != 0) {
                //self.automaticallyAdjustsScrollViewInsets = YES;
                
                [self.view addSubview:self.hostLikeView];
                [self.hostLikeView reloadData];
            }
            
        }];

        
        
        
        
    }
    
    
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.hostLikeView reloadData];
        [self.hostLikeView footerEndRefreshing];
    });
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"赞过的";
    // 调用数据处理的方法
    [self handleData];
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
       self.hostLikeView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.bounds.size.width, self.view.bounds.size.height - 64) style:UITableViewStylePlain];
    
    [_hostLikeView release];
    self.hostLikeView.delegate = self;
    self.hostLikeView.dataSource = self;
    
   
    
    // 注册cell类
    [self.hostLikeView registerClass:[AlbumDetailsCell class] forCellReuseIdentifier:@"like"];
    
    
    
    [self setupRefresh];
}

#pragma mark section的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.arr count];
}

#pragma mark cell的设置
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    static NSString *str = @"datails";
    
    AlbumDetailsCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    
    if (cell == nil || self.cellTag != 10000 + indexPath.row) {
        
        cell = [[[AlbumDetailsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str] autorelease];
        [cell.audioButton addTarget:self action:@selector(playLikeAudio:) forControlEvents:UIControlEventTouchUpInside];
    }
    cell.audioButton.tag = indexPath.row + 10000;
    
    if (self.cellTag == 10000 + indexPath.row) {
        [cell.audioButton removeFromSuperview];
        [cell.contentView addSubview:self.audioBtn];
    }
    AlbumDatailsOfList *datailList = [self.arr objectAtIndex:indexPath.row];
    
    NSLog(@"%ld",cell.audioButton.tag);
    
    
    cell.albumDatailsOfList = datailList;
    
    return cell;

    
    
    

    
    
    
//    AlbumDetailsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"like"];
//    AlbumDatailsOfList *albumList = [self.arr objectAtIndex:indexPath.row];
//    
//   cell.albumDatailsOfList = albumList;
    //cell.textLabel.text = albumList.title;
    
    
    return cell;
}


#pragma mark 点击播放的按钮

- (void)playLikeAudio:(AudioButton *)button
{
    
    self.audioBtn = button;
    self.cellTag = button.tag;
    _audioPlayer =  [AudioPlayer shareInstance];
    _audioPlayer.imagePath = [[self.arr objectAtIndex:button.tag - 10000] coverLarge];
    
    if ([_audioPlayer.button isEqual: button]) {
        
        [_audioPlayer play];
        
    } else {
        _mainPlayVC = [MainPlayerViewController defaultPlayer];
        _mainPlayVC.trackId = [[self.arr objectAtIndex:button.tag - 10000] trackId];
        _mainPlayVC.index = button.tag - 10000;
        [_mainPlayVC.listArr removeAllObjects];
        [_mainPlayVC.listArr addObjectsFromArray:self.arr];
        [_mainPlayVC showDetailInformation];
        [_audioPlayer stop];
        
        _audioPlayer.button = button;
        
        
        _audioPlayer.url = [NSURL URLWithString:[[self.arr objectAtIndex:button.tag - 10000] playUrl64]];
        
        [_audioPlayer play];
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (void)viewWillAppear:(BOOL)animated
{
    
    self.navigationController.navigationBar.translucent = YES;
    
}

#pragma mark 点击cell

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    self.cell = (AlbumDetailsCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    AlbumDatailsOfList *dataList = [self.arr objectAtIndex:indexPath.row];
    
    _mainPlayVC = [MainPlayerViewController defaultPlayer];
    
    
    _mainPlayVC.albumDatail = dataList;
    _mainPlayVC.trackId = dataList.trackId;
    [_mainPlayVC.listArr removeAllObjects];
    [_mainPlayVC.listArr addObjectsFromArray:self.arr];
    _mainPlayVC.index = indexPath.row;
    _mainPlayVC.navi = self.navigationController;
    _audioPlayer = [AudioPlayer shareInstance];
    
    if (![_audioPlayer.button isEqual:_cell.audioButton]) {
        
        [_audioPlayer stop];
        self.audioBtn = _cell.audioButton;
        
        _audioPlayer.button = _cell.audioButton;
        self.cellTag = _cell.audioButton.tag;
        _audioPlayer.url = [NSURL URLWithString:dataList.playUrl64];
        [_audioPlayer play];
        
    }
    
    
    // _mainPlayVC.audioButton = _cell.audioButton;
    
    [_mainPlayVC showDetailInformation];
    
    CATransition *transition = [CATransition animation];
    transition.duration = 0.3f;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = @"push";
    transition.subtype = kCATransitionFromTop;
    transition.delegate = self;
    [self.navigationController.view.layer addAnimation:transition forKey:nil];
    [self.navigationController pushViewController:_mainPlayVC animated:NO];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)dealloc
{
    [_arr release];
    [_hostLikeView release];
    
    [super dealloc];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
